<template>
  <el-dialog
    v-model="dialogVisible"
    append-to-body
    title="数据请求"
    width="800"
    @close="close"
    :destroy-on-close="true"
  >
    <div class="select-none">
      <el-button type="primary" text disabled>全局公共配置</el-button>
      <div class="flex items-center mt-[10px]">
        <span class="text-[#ccc] whitespace-nowrap flex items-center">
          <span>是否使用数据源</span>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="选择使用数据源后将不用配置服务地址URL"
            placement="top-start"
          >
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip> </span
        >：
        <el-switch
          v-model="sourceInfo.ifDataSource"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </div>
      <div class="flex items-center mt-[10px]" v-if="sourceInfo.ifDataSource">
        <span class="text-[#ccc] whitespace-nowrap flex items-center">
          <span>请选择数据源</span>

          <el-tooltip
            class="box-item"
            effect="dark"
            content="请在数据源配置页面进行数据源管理"
            placement="top-start"
          >
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
          ：
        </span>
        <el-select
          v-model="sourceInfo.dataSourceId"
          placeholder="选择数据源"
          @change="changeDataSource"
          style="width: 200px"
        >
          <el-option
            v-for="(item, index) in dataSourceList"
            :key="item.id"
            :label="item.serviceName"
            :value="item.id"
          />
        </el-select>
      </div>

      <div class="flex items-center mt-[10px]" v-if="!sourceInfo.ifDataSource">
        <span class="text-[#ccc] whitespace-nowrap">服务地址URL：</span>
        <el-input
          clearable
          v-model="states.baseUrl"
          class="w-[590px!important]"
          type="text"
          placeholder="例：http://127.0.0.1:8080"
        />
      </div>

      <div class="flex items-center mt-[10px]">
        <span class="text-[#ccc] whitespace-nowrap">是否轮询更新？</span>
        <el-switch
          v-model="states.ifPolling"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </div>
      <div class="flex items-center mt-[10px]" v-if="states.ifPolling">
        <span class="text-[#ccc] whitespace-nowrap">轮询间隔时间：</span>
        <!-- <el-input
          v-model="states.pollingTime"
          class="w-[200px!important]"
          type="text"
          placeholder="单位为毫秒，例：1000"
        /> -->
        <el-input-number
          placeholder="单位为毫秒"
          class="w-[200px!important]"
          v-model="states.pollingTime"
          :step="1000"
        />
      </div>
      <div class="flex items-center mt-[10px]">
        <span class="text-[#ccc] whitespace-nowrap">页面加载时调用?</span>
        <el-switch
          v-model="states.ifInit"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </div>
    </div>
    <div class="w-[99%] h-[1px] mx-auto my-[10px]"></div>

    <div class="flex items-center mb-[20px]">
      <span class="mx-[30px]">路径</span>

      <el-input
        v-model="states.url"
        style="max-width: 600px"
        placeholder="例：/query"
        class="input-with-select"
      >
        <template #prepend>
          <el-select
            v-model="states.method"
            placeholder="请求方式"
            style="width: 115px"
          >
            <el-option
              v-for="(item, index) in SelecList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
      </el-input>
    </div>
    <div class="flex items-start">
      <span class="mx-[30px] whitespace-nowrap">参数</span>

      <el-tabs
        v-model="activeName"
        @tab-change="tabChange"
        class="bg-[#232324] w-[600px]"
      >
        <el-tab-pane label="Header" name="Header" class="bg-[#232324]">
          <el-table
            :data="headersValue"
            style="width: 100%"
            class="mb-[20px]"
            header-row-class-name="headerClass"
          >
            <el-table-column prop="Key" label="Key" width="180">
              <template #default="scope">
                <el-input v-model="scope.row.Key" />
              </template>
            </el-table-column>
            <el-table-column prop="Value" label="Value" width="180">
              <template #default="scope">
                <el-input v-model="scope.row.Value" /> </template
            ></el-table-column>
            <el-table-column prop="address" label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="handlePlusHeader(scope.$index, scope.row, 'params')"
                >
                  +
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDeleteHeader(scope.$index, scope.row, 'params')"
                >
                  -
                </el-button>
              </template>
            </el-table-column>

            <template #empty>
              <el-button
                size="small"
                @click="handlePlusHeader(0, {}, 'params')"
              >
                +
              </el-button>
            </template>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="Params" name="Params" class="bg-[#232324]">
        </el-tab-pane>
        <el-tab-pane label="Body" name="Body" class="bg-[#232324]">
          <el-radio-group
            v-model="bodyType"
            class="mb-[10px]"
            @change="changeType"
          >
            <el-radio :value="1">none</el-radio>
            <el-radio :value="2">form-data</el-radio>
            <el-radio :value="3">x-www-form-urlencoded</el-radio>
          </el-radio-group>
        </el-tab-pane>
        <el-table
          v-if="showTable && activeName != 'Header'"
          :data="queryParams"
          style="width: 100%"
          class="mb-[20px]"
          header-row-class-name="headerClass"
        >
          <el-table-column prop="Key" label="Key" width="180">
            <template #default="scope">
              <el-input v-model="scope.row.Key" />
            </template>
          </el-table-column>
          <el-table-column prop="Value" label="Value" width="180">
            <template #default="scope">
              <el-input v-model="scope.row.Value" /> </template
          ></el-table-column>
          <el-table-column prop="address" label="操作">
            <template #default="scope">
              <el-button
                size="small"
                @click="handlePlus(scope.$index, scope.row, 'params')"
              >
                +
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row, 'params')"
              >
                -
              </el-button>
            </template>
          </el-table-column>

          <template #empty>
            <el-button size="small" @click="handlePlus(0, {}, 'params')">
              +
            </el-button>
          </template>
        </el-table>
      </el-tabs>
    </div>
    <!-- </div> -->

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import {
  getDataSourceListNoPage,
  getDataSourceDetail,
} from "@renderer/api/dataSource";
import { useBaseConfigStore } from "@renderer/store/modules/baseConfig";
const baseConfigStore = useBaseConfigStore();

const props = defineProps({
  request: {
    type: Object,
    default: () => ({}),
  },
  layoutItem: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(["save", "saveSource", "close"]);

const sourceInfo = ref<any>({});
const states = ref<any>({});
const init = (value) => {
  queryDataSource();
  states.value = JSON.parse(JSON.stringify(value));
  sourceInfo.value = {
    ifDataSource: props.layoutItem.ifDataSource,
    dataSourceId: props.layoutItem.dataSourceId,
    dataSourceInfo: props.layoutItem.dataSourceInfo,
  };
};

onMounted(() => {
  // console.log("onMounted");
});
const dataSourceList = ref([]);
const queryDataSource = async () => {
  const res: any = await getDataSourceListNoPage({});
  if (res.code == 200) {
    dataSourceList.value = res.data;
  }
};
const changeDataSource = (val: string) => {
  // console.log(val);
  getDataSourceDetail({ id: val }).then((res: any) => {
    if (res.code == 200) {
      sourceInfo.value.dataSourceInfo = res.data;
    }
  });
};

const dialogVisible = ref(false);
const activeName = ref("Params");

const SelecList = ["get", "post", "put", "delete", "patch"];
const bodyType = ref(3);
const showTable = ref(true);
const queryParams = ref([]);
const headersValue = ref([]);
const handleParams = () => {
  let obj = {};

  queryParams.value.forEach((item) => {
    obj[item.Key] = item.Value;
  });
  return obj;
};
const handleBodys = () => {
  let obj = {};
  if (bodyType.value == 2 && activeName.value == "Body") {
    states.value.ifFormData = true;
    queryParams.value.forEach((item) => {
      obj[item.Key] = item.Value;
    });
    return obj;
  } else {
    states.value.ifFormData = false;
    queryParams.value.forEach((item) => {
      obj[item.Key] = item.Value;
    });
    return obj;
  }
};
const handelHeaders = () => {
  let obj = {};
  headersValue.value.forEach((item) => {
    obj[item.Key] = item.Value;
  });
  return obj;
};
watch(dialogVisible, () => {
  if (dialogVisible.value) {
    if (Object.keys(props.request.headers).length > 0) {
      let headersArr = [];
      Object.keys(props.request.headers).forEach((it) => {
        headersArr.push({
          Key: it,
          Value: props.request.headers[it],
        });
      });
      headersValue.value = headersArr;
    }

    if (Object.keys(props.request.params).length > 0) {
      activeName.value = "Params";
      let paramsArr = [];
      Object.keys(props.request.params).forEach((it) => {
        paramsArr.push({
          Key: it,
          Value: props.request.params[it],
        });
      });
      queryParams.value = paramsArr;
    }

    if (props.request.ifFormData) {
      activeName.value = "Body";
      bodyType.value = 2;
    }
    if (props.request.data instanceof FormData) {
      // console.log("props.request.data", props.request.data);
      activeName.value = "Body";
      bodyType.value = 2;
      let bodyArr = [];
      for (const [key, value] of (props.request.data as any).entries()) {
        bodyArr.push({
          Key: key,
          Value: value,
        });
      }
      queryParams.value = bodyArr;
    } else if (Object.keys(props.request.data).length > 0) {
      activeName.value = "Body";
      let bodyArr = [];
      if (props.request.ifFormData) {
        bodyType.value = 2;
      }
      Object.keys(props.request.data).forEach((it) => {
        bodyArr.push({
          Key: it,
          Value: props.request.data[it],
        });
      });

      queryParams.value = bodyArr;
    }
  }
});

watch(
  [() => activeName, () => queryParams.value, () => bodyType.value],
  () => {
    if (activeName.value == "Params") {
      states.value.params = handleParams();
      states.value.data = {};
      states.value.ifFormData = false;
    } else if (activeName.value == "Body") {
      states.value.data = handleBodys();
      states.value.params = {};
    }
    if (bodyType.value == 1) {
      states.value.ifFormData = false;
      states.value.data = {};
    }
  },

  {
    immediate: true,
    deep: true,
  }
);
watch(
  () => headersValue.value,
  () => {
    states.value.headers = handelHeaders();
  },
  {
    immediate: true,
    deep: true,
  }
);

const handlePlus = (index: number, item: any, type: string) => {
  queryParams.value.push({
    Key: "",
    Value: "",
  });
};
const handlePlusHeader = (index: number, item: any, type: string) => {
  headersValue.value.push({
    Key: "",
    Value: "",
  });
};
const handleDelete = (index: number, item: any, type: string) => {
  queryParams.value.splice(index, 1);
};
const handleDeleteHeader = (index: number, item: any, type: string) => {
  headersValue.value.splice(index, 1);
};
const changeType = () => {
  showTable.value = bodyType.value != 1;
};
const tabChange = () => {
  if (activeName.value == "Params") showTable.value = true;
  if (activeName.value == "Header") showTable.value = true;
  if (activeName.value == "Body") {
    changeType();
  }
};

const save = () => {
  if (sourceInfo.value.ifDataSource && sourceInfo.value.dataSourceId == "") {
    ElMessage({
      message: "请选择数据源",
      type: "error",
    });
    return;
  }
  if (!sourceInfo.value.ifDataSource && states.value.baseUrl == "") {
    ElMessage({
      message: "请输入服务地址",
      type: "error",
    });
    return;
  }
  if (states.value.ifPolling && !states.value.pollingTime) {
    ElMessage({
      message: "请输入正确的轮询间隔时间",
      type: "error",
    });
    return;
  }
  // console.log("state", states.value);

  emit("save", states.value);
  emit("saveSource", sourceInfo.value);
  ElMessage({
    message: "保存成功",
    type: "success",
  });
  dialogVisible.value = false;
};

const close = () => {
  emit("close");
  dialogVisible.value = false;
};

defineExpose({
  dialogVisible,
  init,
});
</script>

<style scoped lang="scss">
:deep(.el-table tr) {
  background-color: #232324 !important;
}
:deep(.el-table th.el-table__cell) {
  background: #39393e !important;
}

:deep(
    .el-input__wrapper,
    .el-input__inner,
    .el-input .el-input-group__prepend,
    .el-select .el-select__wrapper
  ) {
  background: #39393e !important;
}

:deep(.el-input-group__prepend) {
  background: #39393e !important;
}

:deep(.el-tabs__nav-wrap:after) {
  background-color: #646567 !important;
}

:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom-color: #646567 !important;
}
:deep(.el-table td.el-table__cell) {
  border-bottom-color: #646567 !important;
}
:deep(.el-table__inner-wrapper:before) {
  height: 0 !important;
}
</style>
